﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using RayD.Core;
using RayD.Repository.Entites.SystemModule;
using RayD.App.SystemModule;

namespace RayD.WebApi.Controllers.Admin
{
    /// <summary>
    /// 个人基本资料资源
    /// </summary>
    public class UserCenterController : BaseAdminController
    {
        #region 构造函数注入
        private UserApp _User;
        public UserCenterController(UserApp User)
        {
            this._User = User;
        }
        #endregion

        #region 参数实体
        /// <summary>
        /// 修改密码请求参数
        /// </summary>
        public class ReviseRequest
        {
            /// <summary>
            /// 旧密码 （MD5 小写）
            /// </summary>
            public string OldPwd { get; set; }
            /// <summary>
            /// 新密码 （MD5 小写）
            /// </summary>
            public string Pwd { get; set; }
        }
        #endregion

        #region 获取数据

        /// <summary>
        /// 获取当前用户个人资料
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResParameter<UserInfo> GetUserInfo()
        {
            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.headIcon.IsEmpty())
            {
                var fileInfo = IOHelper.Read(userInfo.headIcon);
                if (!fileInfo.IsEmpty())
                    userInfo.headIcon = $"data:{ fileInfo.ContentType };base64,{ Base64Helper.FileToBase64(fileInfo.FileStream) }";
            }
            return Success(userInfo);
        }

        #endregion

        #region 提交数据
        /// <summary>
        /// 上传用户头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResParameter<string> UploadFile()
        {
            string base64Res;
            //保存到硬盘
            var fileInfo = IOHelper.Save(AppSettings.UploadPath.fileHeadImg);
            //没有文件上传，直接返回
            if (fileInfo.IsEmpty())
            {
                return Fail<string>("");
            }
            else
            {
                base64Res = $"data:{ fileInfo.ContentType };base64,{ Base64Helper.FileToBase64(fileInfo.FileStream) }";
            }
            //保存到数据库
            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;
            UserEntity userEntity = new UserEntity()
            {
                B_UserId = userInfo.userId
                ,
                B_HeadIcon = fileInfo.VirtualPath
            };
            var (isSuccess, msg) = _User.SaveForm(userEntity);
            if (isSuccess)
            {
                return Success<string>(base64Res);
            }
            else
            {
                return Fail<string>("");
            }
        }

        /// <summary>
        /// 保存个人信息设置
        /// </summary>
        /// <returns></returns>
        [HttpPut, Logging("个人信息设置")]
        public ResParameter SaveForm(UserInfo request)
        {
            UserEntity userEntity = new UserEntity();
            userEntity.B_UserId = request.userId;
            userEntity.B_RealName = request.realName;
            userEntity.B_Gender = request.gender;
            userEntity.B_Birthday = request.birthday;
            userEntity.B_Mobile = request.mobile;
            userEntity.B_Telephone = request.telephone;
            userEntity.B_Email = request.email;
            userEntity.B_OICQ = request.oICQ;
            userEntity.B_WeChat = request.weChat;

            var (isSuccess, msg) = _User.SaveForm(userEntity);
            if (isSuccess)
            {
                return Success("修改成功！");
            }
            else
            {
                return Fail(msg);
            }
        }
        /// <summary>
        /// 修改当前用户密码
        /// </summary>
        /// <returns></returns>
        [HttpPut, Logging("个人密码修改")]
        public ResParameter RevisePassword(ReviseRequest request)
        {
            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;
            if (userInfo.isSystem)
            {
                return Fail("系统管理员账号无法修改！");
            }

            var (isSuccess, msg) = _User.RevisePassword(request.OldPwd, request.Pwd);
            if (isSuccess)
            {
                //清除登录信息
                AuthenticationHelper.Clear();
                return Success(msg);
            }
            else
            {
                return Fail(msg);
            }
        }
        #endregion

        #region 数据验证

        /// <summary>
        /// 验证旧密码
        /// </summary>
        /// <param name="OldPwd">旧密码 （MD5 小写）</param>
        /// <returns></returns>
        [HttpGet]
        public ResParameter ValidateOldPwd(string OldPwd)
        {
            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;
            UserEntity userEntity = _User.GetEntityById(userInfo.userId);
            OldPwd = Md5Helper.Encrypt(DESEncrypt.Encrypt(OldPwd, userEntity.B_Secretkey).ToLower(), 32).ToLower();
            if (OldPwd == userEntity.B_Password)
            {
                return Success("验证通过！");
            }
            else
            {
                return Fail("密码错误，请重新输入！");
            }
        }

        #endregion
    }
}
